<template>
    <div class="list-container">
        <div class='search-area'>
            <div class='search-left'>
                <div class='input-line'>
                    <span class='label'>搜索关键词：</span>
                    <el-input placeholder="请输入商户名" label='商户名' v-model="searchParams.keyword"/>
                </div>
            </div>
            <div class='search-right'>
                <el-button type="primary" @click='onSearchClick'>查询</el-button>
                <el-button type="primary" @click='onDialogOpen'>新增轮播图</el-button>
            </div>
        </div>
        <el-table
            fit
            :data="tableData"
            style="width: 100%">
            <el-table-column
                prop="carouselPic"
                label="轮播图主图">
                <template slot-scope="scope">
                    <img class="thumbnail" :src="scope.row.carouselPic" alt="">
                </template>
            </el-table-column>
            <el-table-column
                prop="firstLevelTitle"
                label="一级标题">
            </el-table-column>
            <el-table-column
                prop="secondLevelTitle"
                label="二级标题">
            </el-table-column>
            <el-table-column
                prop="content"
                label="轮播图简介">
            </el-table-column>
            <el-table-column
                prop="jumpUrl"
                label="购买链接">
                <template slot-scope="scope">
                    <a :href="scope.row.jumpUrl" target="_blank">{{ scope.row.jumpUrl }}</a>
                </template>
            </el-table-column>
            <el-table-column
                prop="sortIndex"
                label="轮播图索引">
            </el-table-column>
            <el-table-column
                prop="viewType"
                label="显示端">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.viewType === 0">全端</el-tag>
                    <el-tag v-if="scope.row.viewType === 1" type="warning">PC端</el-tag>
                    <el-tag v-if="scope.row.viewType === 2" type="danger">移动端</el-tag>
                </template>
            </el-table-column>
            <el-table-column
                prop="typeId"
                label="语言类型">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.languageType === 'ch'" type="warning">中文</el-tag>
                    <el-tag v-if="scope.row.languageType === 'en'" type="danger">英文</el-tag>
                    <el-tag v-if="scope.row.languageType === 'fan'" type="success">繁体</el-tag>
                </template>
            </el-table-column>

            <el-table-column
                align='center'
                label="操作"
                width='200'>
                <template slot-scope="scope">
                    <div style='display: flex;align-items: center;flex-wrap: wrap'>
                        <el-button type='primary' size='mini' @click='onDeleteClick(scope.row.id)'>删除</el-button>
                        <el-button type='primary' size='mini' @click='handleModify(scope.row.id)'>修改</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div class='pagination'>
            <el-pagination
                background
                layout="prev, pager, next"
                :current-page='currentPage'
                :page-size='10'
                :total="total"
                @current-change='onPageChange'
            >
            </el-pagination>
        </div>

        <!--   新增轮播图弹框     -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" @close="onDialogClose()">
            <el-form ref="dataForm" :rules="rules" :model="addForm" label-width="80px">
                <el-form-item label="轮播图" prop="carouselPic">
                    <el-upload
                        action="http://8.137.53.59:8888/api/common/upload"
                        list-type="picture-card"
                        :limit="1"
                        :file-list="carouselPicList"
                        :before-upload="handleBeforeUpload"
                        :on-success="handleUploadSuccess"
                        :on-remove="handleRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <div class="upload-notice">*图片尺寸：1920×980，或符合该宽高比例的图片</div>
                </el-form-item>
                <el-form-item label="语言类型" prop="languageType">
                    <el-radio-group v-model="addForm.languageType">
                        <el-radio-button label="ch">中文</el-radio-button>
                        <el-radio-button label="en">英文</el-radio-button>
                        <el-radio-button label="fan">繁体</el-radio-button>
                    </el-radio-group>
                    <div class="upload-notice">首页轮播图相关内容，请所选择的语言类型！</div>
                </el-form-item>
                <el-form-item label="显示类型" prop="viewType">
                    <el-radio-group v-model="addForm.viewType">
                        <el-radio-button label="0">全端</el-radio-button>
                        <el-radio-button label="1">PC端</el-radio-button>
                        <el-radio-button label="2">移动端</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="轮播索引" prop="sortIndex">
                    <el-input-number v-model="addForm.sortIndex" :min="0" label="轮播索引"></el-input-number>
                </el-form-item>
                <el-form-item label="一级标题" prop="firstLevelTitle">
                    <el-input v-model="addForm.firstLevelTitle" placeholder="一级标题"></el-input>
                </el-form-item>
                <el-form-item label="二级标题" prop="secondLevelTitle">
                    <el-input v-model="addForm.secondLevelTitle" placeholder="二级标题"></el-input>
                </el-form-item>
                <el-form-item label="轮播简介" prop="content">
                    <el-input v-model="addForm.content" placeholder="轮播图简介"></el-input>
                </el-form-item>
                <el-form-item label="跳转链接" prop="jumpUrl">
                    <el-input v-model="addForm.jumpUrl" placeholder="跳转链接"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="onDialogSubmit('modify')" v-if="addForm.id">确认修改</el-button>
                <el-button type="primary" @click="onDialogSubmit('add')" v-else>立即创建</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { getCarouselList, addCarousel, deleteCarousel, getCarouselDetail, updateCarousel } from '@/api/carousel'
    export default {
        data() {
            return {
                searchParams: {
                    pageSize: 10,
                    keyword: '', // 关键词搜索
                },
                currentPage: 1,
                total: 0,
                tableData: [],
                dialogVisible: false,
                addForm: {
                    languageType: 'ch', // 语言类型 en:英文 ch:中文
                    sortIndex: 0, // 轮播图索引，用于排序
                    carouselPic: '', // 主图
                    firstLevelTitle: '', // 一级标题
                    secondLevelTitle: '', // 二级标题
                    content: '', // 简介
                    jumpUrl: '', // 购买链接
                    detailText: '', // 轮播图介绍富文本
                    viewType: 0, // 显示控制 0：全部 1：PC 2：移动端
                },
                rules: {
                    carouselPic: [
                        {
                            required: true,
                            message: '请上传轮播图',
                            trigger: 'blur'
                        },
                    ],
                    languageType: [
                        {
                            required: true,
                            message: '请选择语言类型',
                            trigger: 'blur'
                        },
                    ],
                    viewType: [
                        {
                            required: true,
                            message: '请选择显示端类型',
                            trigger: 'blur'
                        },
                    ],
                    firstLevelTitle: [
                        {
                            required: true,
                            message: '一级标题不能为空',
                            trigger: 'blur'
                        }
                    ],
                    secondLevelTitle: [
                        {
                            required: true,
                            message: '二级标题不能为空',
                            trigger: 'blur'
                        }
                    ],
                    content: [
                        {
                            required: true,
                            message: '轮播图简介不能为空',
                            trigger: 'blur'
                        }
                    ],
                    jumpUrl: [
                        {
                            required: true,
                            message: '轮播图跳转链接不能为空',
                            trigger: 'blur'
                        }
                    ]
                },
                dialogTitle: '新增轮播图',
                carouselPicList: [], // 主图列表
            }
        },
        mounted() {
            this.getCarouselListFn()
        },
        methods: {
            onPageChange(page) {
                this.currentPage = page
            },

            onSearchClick() {
                this.getCarouselListFn(1)
            },

            // 获取轮播图列表数据
            async getCarouselListFn(currentPage) {
                let requestParams = this.searchParams
                requestParams.pageIndex = this.currentPage
                const data = await getCarouselList(requestParams)
                this.total = +data.total
                this.currentPage = +data.pageIndex || 1
                this.tableData = data.list
            },

            // 显示轮播图添加弹框
            onDialogOpen() {
                this.dialogVisible=true
            },
            // 关闭轮播图添加弹窗
            onDialogClose() {
                this.dataForm.tempRoleIds = []
                this.$refs.dataForm.resetFields()
            },

            // 轮播图添加弹框提交
            onDialogSubmit(type) {
                if (type === 'modify') {
                    this.modifyCarouselFn()
                } else {
                    this.addCarouselFn()
                }
            },

            // 轮播编辑
            async handleModify(id) {
                this.dialogVisible = true

                let requestParams = {id}
                let res = await getCarouselDetail(requestParams)

                this.addForm.id = res.id
                this.addForm.carouselPic = res.carouselPic
                this.addForm.firstLevelTitle = res.firstLevelTitle
                this.addForm.secondLevelTitle = res.secondLevelTitle
                this.addForm.content = res.content
                this.addForm.languageType = res.languageType
                this.addForm.jumpUrl = res.jumpUrl
                this.addForm.sortIndex = res.sortIndex

                this.carouselPicList = [{name: 'carouselPic', url: res.carouselPic}]
            },

            // 删除已上传的图片
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },

            // 图片上传前校验
            handleBeforeUpload(file) {
                let _this = this;
                return new Promise((resolve, reject) => {
                    let reader = new FileReader()
                    reader.readAsDataURL(file);
                    reader.onload = function () {
                        let img = document.createElement("img");
                        img.src = this.result;
                        img.onload = function () {
                            console.log(img.width)
                            console.log(img.height)
                            let imgRate =  +((img.width / img.height).toFixed(4))
                            if (imgRate === 1.9592) {
                                return resolve(true)
                            } else {
                                _this.$message.error('请上传符合比例的图片!（宽高比：1.9592）');
                                return reject(false)
                            }
                        }
                    }
                })
            },

            // 图片上传成功
            handleUploadSuccess(file) {
                const { code, data, msg } = file
                if (code === 200) {
                    this.addForm.carouselPic = data.url
                } else {
                    this.$message.error(msg)
                }
                console.log(file, '图片上传结果')
            },

            // 添加轮播图
            async addCarouselFn() {
                let requestParams = this.addForm
                const data = await addCarousel(requestParams)
                this.dialogVisible = false
                this.$message.success('轮播图添加成功')
                this.getCarouselListFn()
                window.location.reload()
            },

            // 修改轮播图
            async modifyCarouselFn() {
                let requestParams = this.addForm
                const data = await updateCarousel(requestParams)
                this.dialogVisible = false
                this.$message.success('轮播图修改成功')
                this.getCarouselListFn()
                window.location.reload()
            },

            // 删除轮播图
            onDeleteClick(id) {
                this.$confirm('此操作将永久删除该轮播图, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const data = await deleteCarousel({id})
                    this.$message.success('删除成功')
                    this.getCarouselListFn()
                })
            },

            // 查看轮播图富文本信息
            onDetailPreviewClick(detailText) {
                this.currentDetailText = detailText
                this.detailTextDialogVisible = true
            },
        }
    }
</script>
<style lang='scss'>
    .list-container{
        .thumbnail{
            width: 100px;
        }
        .detail-text-preview{
            img{
                max-width: 100%;
            }
        }
        .search-area{
            display: flex;
            align-items: center;
            width: 100%;
            padding: 20px 0;
            border-bottom: 1px solid #f2f2f2;
            .search-left{
                display: flex;
                align-items: center;
                justify-content: center;
                .input-line{
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin-right: 20px;
                    .label{
                        flex-shrink: 0;
                    }
                    .gap{
                        padding: 0 10px;
                    }
                }
            }
            .search-right{
                display: flex;
                justify-content: flex-end;
                margin-left: 20px;
            }
        }
        .pagination{
            margin-top: 20px;
        }
        .upload-notice{
            color: red;
        }
    }
</style>
